/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.restaurant.entity.CommoditySummary;
import org.springblade.modules.restaurant.entity.PurchaseCategory;
import org.springblade.modules.restaurant.entity.PurchaseCommodity;
import org.springblade.modules.restaurant.enums.CommodityArrivalEnums;
import org.springblade.modules.restaurant.excel.CommoditySummaryExcel;
import org.springblade.modules.restaurant.service.ICommodityRecordRelationService;
import org.springblade.modules.restaurant.service.ICommoditySummaryService;
import org.springblade.modules.restaurant.service.IPurchaseCategoryService;
import org.springblade.modules.restaurant.service.IPurchaseCommodityService;
import org.springblade.modules.restaurant.vo.CommoditySummaryVO;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 货物采购汇总表 控制器
 *
 * @author Blade
 * @since 2025-02-05
 */
@RestController
@AllArgsConstructor
@RequestMapping("/restaurant/commoditysummary")
@Tag(name = "货物采购汇总表", description = "货物采购汇总表接口")
public class CommoditySummaryController extends BladeController {

	private ICommoditySummaryService commoditySummaryService;
	private ICommodityRecordRelationService commodityRecordRelationService;
	private IPurchaseCommodityService purchaseCommodityService;
	private IPurchaseCategoryService purchaseCategoryService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入commoditySummary")
	public R<CommoditySummary> detail(CommoditySummary commoditySummary) {
		CommoditySummary detail = commoditySummaryService.getOne(Condition.getQueryWrapper(commoditySummary));
		return R.data(detail);
	}

	/**
	 * 分页 货物采购汇总表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入commoditySummary")
	public R<IPage<CommoditySummary>> list(CommoditySummaryVO commoditySummary, Query query) {
		LambdaQueryWrapper<CommoditySummary> wrapper = customizeQueryWrapper(commoditySummary);
		IPage<CommoditySummary> pages = commoditySummaryService.page(Condition.getPage(query), wrapper);
		return R.data(pages);
	}

	/**
	 * 自定义分页 货物采购汇总表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description = "传入commoditySummary")
	public R<IPage<CommoditySummaryVO>> page(CommoditySummaryVO commoditySummary, Query query) {
		IPage<CommoditySummaryVO> pages = commoditySummaryService.selectCommoditySummaryPage(Condition.getPage(query), commoditySummary);
		return R.data(pages);
	}

	/**
	 * 新增 货物采购汇总表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description = "传入commoditySummary")
	public R save(@Valid @RequestBody CommoditySummary commoditySummary) {
		if (ObjectUtil.isNotNull(commoditySummary.getCategoryId())) {
			Long categoryId = commoditySummary.getCategoryId();
			PurchaseCategory purchaseCategory = purchaseCategoryService.getById(categoryId);
			commoditySummary.setCategoryName(purchaseCategory.getCategoryName());
			commoditySummary.setSort(purchaseCategory.getSort());
		}
		if (ObjectUtil.isNotNull(commoditySummary.getCommodityId())) {
			Long commodityId = commoditySummary.getCommodityId();
			PurchaseCommodity commodity = purchaseCommodityService.getById(commodityId);
			commoditySummary.setCommodityName(commodity.getCommodityName());
			commoditySummary.setUnit(commodity.getUnit());
			commoditySummary.setProductPicture(commodity.getProductPicture());
		}

		//根据金额 和实到数量 计算单价
		BigDecimal unitPrice = BigDecimal.ZERO;
		BigDecimal difference = BigDecimal.ZERO;
		BigDecimal actualNumber = BigDecimal.ZERO;
		if (ObjectUtil.isNotNull(commoditySummary.getAmount())
			&& ObjectUtil.isNotNull(commoditySummary.getActualNumber())
			&& commoditySummary.getActualNumber().compareTo(BigDecimal.ZERO) > 0
		) {
			actualNumber = commoditySummary.getActualNumber();
			unitPrice = commoditySummary.getAmount().divide(actualNumber, 2, RoundingMode.HALF_UP);
		}
		// 实到数量 - 申购数量 = 数量差额
		difference = actualNumber.subtract(BigDecimal.valueOf(commoditySummary.getNumber()));
		commoditySummary.setUnitPrice(unitPrice);
		commoditySummary.setDifference(difference);

		// 如果实到数量填写0，则状态为未到货
		commoditySummary.setStatus(CommodityArrivalEnums.ARRIVAL.getCode());
		if (commoditySummary.getActualNumber().compareTo(BigDecimal.ZERO) == 0) {
			commoditySummary.setStatus(CommodityArrivalEnums.NOT_ARRIVAL.getCode());
		}

		Integer status = commoditySummary.getStatus();
		if (CommodityArrivalEnums.CANCEL_ORDER.getCode().equals(status)) {
			commoditySummary.setStatus(CommodityArrivalEnums.CANCEL_ORDER.getCode());
		} else {
			if (commoditySummary.getActualNumber().compareTo(BigDecimal.ZERO) == 0) {
				commoditySummary.setStatus(CommodityArrivalEnums.NOT_ARRIVAL.getCode());
			} else {
				commoditySummary.setStatus(CommodityArrivalEnums.ARRIVAL.getCode());
			}
		}
		// 是否补单: 0 否 1 是
		commoditySummary.setIsReplacement(1);
		return R.status(commoditySummaryService.save(commoditySummary));
	}

	/**
	 * 修改 货物采购汇总表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description = "传入commoditySummary")
	public R update(@Valid @RequestBody CommoditySummary commoditySummary) {
		return R.status(commoditySummaryService.updateById(commoditySummary));
	}

	/**
	 * 新增或修改 货物采购汇总表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入commoditySummary")
	public R submit(@Valid @RequestBody CommoditySummary commoditySummary) {
		//根据金额 和实到数量 计算单价
		BigDecimal unitPrice = BigDecimal.ZERO;
		BigDecimal difference = BigDecimal.ZERO;
		BigDecimal actualNumber = BigDecimal.ZERO;
		if (ObjectUtil.isNotNull(commoditySummary.getAmount())
			&& ObjectUtil.isNotNull(commoditySummary.getActualNumber())
			&& commoditySummary.getActualNumber().compareTo(BigDecimal.ZERO) > 0
		) {
			actualNumber = commoditySummary.getActualNumber();
			unitPrice = commoditySummary.getAmount().divide(actualNumber, 2, RoundingMode.HALF_UP);
		}
		// 实到数量 - 申购数量 = 数量差额
		difference = actualNumber.subtract(BigDecimal.valueOf(commoditySummary.getNumber()));
		commoditySummary.setUnitPrice(unitPrice);
		commoditySummary.setDifference(difference);

		// 如果实到数量填写0，则状态为未到货
		commoditySummary.setStatus(CommodityArrivalEnums.ARRIVAL.getCode());
		if (commoditySummary.getActualNumber().compareTo(BigDecimal.ZERO) == 0) {
			commoditySummary.setStatus(CommodityArrivalEnums.NOT_ARRIVAL.getCode());
		}
		String purchaseTime = commoditySummary.getPurchaseTime();
		Long commodityId = commoditySummary.getCommodityId();

		Integer status = commoditySummary.getStatus();
		if (CommodityArrivalEnums.CANCEL_ORDER.getCode().equals(status)) {
			commoditySummary.setStatus(CommodityArrivalEnums.CANCEL_ORDER.getCode());
		} else {
			if (commoditySummary.getActualNumber().compareTo(BigDecimal.ZERO) == 0) {
				commoditySummary.setStatus(CommodityArrivalEnums.NOT_ARRIVAL.getCode());
			} else {
				commoditySummary.setStatus(CommodityArrivalEnums.ARRIVAL.getCode());
			}
		}

		commodityRecordRelationService.updateUnitPrice(purchaseTime, commodityId, unitPrice);
		return R.status(commoditySummaryService.saveOrUpdate(commoditySummary));
	}


	/**
	 * 删除 货物采购汇总表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(commoditySummaryService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 导出采购记录
	 */
	@SneakyThrows
	@GetMapping("/export")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出采购汇总记录", description = "传入commoditySummary")
	public void export(CommoditySummaryVO commoditySummary, HttpServletResponse response) {

		LambdaQueryWrapper<CommoditySummary> wrapper = customizeQueryWrapper(commoditySummary);
		List<CommoditySummary> commoditySummaryList = commoditySummaryService.list(wrapper);
		List<CommoditySummaryExcel> list = commoditySummaryService.exportSummary(commoditySummaryList);

		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("采购汇总", StandardCharsets.UTF_8)
			+ "_" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);

		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), CommoditySummaryExcel.class).sheet("采购汇总").doWrite(list);
	}


	private LambdaQueryWrapper<CommoditySummary> customizeQueryWrapper(CommoditySummaryVO commoditySummary) {

		String[] searchTime = commoditySummary.getSearchTime();
		DateTime now = DateUtil.date();
		// 获取今天开始时间
		String startTime = DateUtil.formatDate(now);
		// 获取当前时间
		String endTime = DateUtil.formatDate(now);

		if (searchTime != null && searchTime.length == 2) {
			startTime = searchTime[0];
			endTime = searchTime[1];
		}
		return Wrappers.<CommoditySummary>lambdaQuery()
			.eq(ObjectUtil.isNotNull(commoditySummary.getCategoryId()), CommoditySummary::getCategoryId, commoditySummary.getCategoryId())
			.like(StrUtil.isNotBlank(commoditySummary.getCommodityName()), CommoditySummary::getCommodityName, commoditySummary.getCommodityName())
			.between(CommoditySummary::getArrivalDate, startTime, endTime)
			.eq(ObjectUtil.isNotNull(commoditySummary.getStatus()), CommoditySummary::getStatus, commoditySummary.getStatus())
			.orderByDesc(CommoditySummary::getArrivalDate).orderByAsc(CommoditySummary::getSort)
			.orderByAsc(CommoditySummary::getId);
	}

}
